import React, { useEffect, useState } from 'react'
import { Upload, Modal } from 'antd'
import { useModel } from '@umijs/max'
import { PlusOutlined } from '@ant-design/icons'
import styles from './index.less'

const UploadForm = React.memo(
  ({ formProps, key, id, onChange, maxCount, disabled, showIcon, ...props }) => {
    const { UPLOAD_URL } = useModel('Global')
    const [fileList, setFileList] = useState([])
    // const [hideButton, setHide] = useState(Boolean(props.value_attribute));
    const [previewOpen, setPreviewOpen] = useState(false)
    const [previewImage, setPreviewImage] = useState('')

    useEffect(() => {
      const value = props.value_attribute || props.value
      if (value) {
        setFileList([
          {
            value_attribute: value,
            url: value
          }
        ])
      } else if (props.fileList) {
        setFileList(props.fileList.map((i) => ({ url: i, value_attribute: i })))
      }
    }, [])

    const UploadButton = () => (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>上传</div>
      </div>
    )

    const handleChange = (e) => {
      if (e.fileList.length) {
        onChange(
          e.fileList
            .filter((i) => i.value_attribute || i.response?.data?.img_url)
            .map((i) => ({
              id,
              key,
              value: i.value_attribute || i.response.data.img_url
            }))
        )
      } else {
        onChange([])
      }
      setFileList(e.fileList)
      // setHide(e.fileList.length >= maxCount);
    }

    const handleCancel = () => setPreviewOpen(false)

    const handlePreview = (e) => {
      setPreviewOpen(true)
      setPreviewImage(e.value_attribute)
    }

    return (
      <div>
        <Upload
          className={maxCount > 1 ? null : styles.avatar_uploader}
          action={UPLOAD_URL}
          onChange={handleChange}
          maxCount={maxCount}
          {...formProps}
          {...props}
          fileList={fileList}
          disabled={disabled}
          onPreview={handlePreview}
        >
          {!disabled && fileList.length < maxCount ? <UploadButton /> : null}
        </Upload>
        {showIcon ? maxCount > 1 ? <div className={styles.corner_tag}>封面</div> : null : null}
        <Modal
          open={previewOpen}
          title={null}
          footer={null}
          onCancel={handleCancel}
        >
          <img alt='example' style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    )
  },
  (prevProps, nextProps) => {
    return prevProps.id === nextProps.id
  }
)

export default UploadForm
